colorAdminApp.controller('userManageController', function($scope,$compile,$rootScope,$http,$state,$stateParams,modalService) {
	
	$scope.easyNgPagination={
			options:{
				        currentPage:1,
				        totalCount:0,
				        pageSize:10,
			            onPageChange: function(){
			 		            	$scope.loadData();
			            }
			}
	};
	
	$scope.items=[];
	$scope.queryEntity={};
	$scope.loadData=function(){
		var currentPage=$scope.easyNgPagination.options.currentPage-1;
		var entity={"page":currentPage,"size":$scope.easyNgPagination.options.pageSize};
		entity["name"]=$scope.queryEntity.name;
		entity["realName"]=$scope.queryEntity.realName;
		entity["departmentName"]=$scope.queryEntity.departmentName;
		entity["email"]=$scope.queryEntity.email;
		$(".dataTables_wrapper").block({ message:'正在加载数据，请稍等...',css: { top: '50%' } });
		$http.post('api/core/access/user/findByPage',{params:entity}).success(function(data, status, headers, config) {
			$scope.items=data.data.content;
			$scope.easyNgPagination.options.totalCount=data.data.totalElements;
			$(".dataTables_wrapper").unblock();
		}).error(function(data, status, headers, config) {
			$(".dataTables_wrapper").unblock();
        });  
	};
	
	
	
	$scope.selectedRoleForAdd=[]; 
	$scope.selectedRoleForEdit=[];
	$scope.entity={};
	$scope.entity.gender="UNKNOWN";
    $scope.editEntity={};
	$scope.editEntity.roleIds=[];
	$scope.roleList=[];
	$scope.roleMap={};
	
	$scope.getRoleList=function(){
		$http.post('api/core/access/role/findAll',{params:{}}).success(function(data, status, headers, config) {
			$scope.roleList=data.data;
			for(var i=0;i<data.length;i++){
				$scope.roleMap["r"+data[i].id]=data[i];
			}
		}).error(function(data, status, headers, config) {
	    	
        });  
	};
	
	$scope.getRoleList();
	
	function convertToIntegerArray(roleIds){
		var retVal=[];
		for(var i=0;i<roleIds.length;i++){
			retVal.push(parseInt(roleIds[i]));
		}
		return retVal;
	}
	
	$scope.showEditModal=function(entity){
		$scope.editEntity=entity;
		$scope.editDepartmentName=entity.departmentName;
		if(entity.roleIds!=undefined&&entity.roleIds!=""){
			$scope.selectedRoleForEdit=convertToIntegerArray(entity.roleIds.split(","));
		}
		$("#editModal").modal("show");	
	};
	
	
	$scope.showAddModal=function(){
		$("#addModal").modal("show");	
	};
	
   $scope.save=function(){
       	$scope.entity.roleIds=$scope.selectedRoleForAdd.join(',');//角色ID

       	delete $scope.entity.gender;
       	var requestJson=JSON.stringify($scope.entity);
   		$(".modal-dialog").block({message:'正在执行操作，请稍等...'});
		$http.post('api/core/access/user/add',{params:{"requestJson":requestJson} }).success(function(data, status, headers, config) {
			$(".modal-dialog").unblock();
			modalService.showAlertModal('注意',data.message);
			if(data.status==1){
				$("#addModal").modal("hide");
				$scope.loadData();
			}
		}).error(function(data, status, headers, config) {
			$(".modal-dialog").unblock();
	    
        });  
	};
	
	$scope.update=function(){
	
	
      	$scope.editEntity.roleIds=$scope.selectedRoleForEdit.join(",");//顺序在arraySubtract方法调用之前
    	
      	var editEntity={};
    	
      	editEntity["id"]=$scope.editEntity.id;
       	editEntity["name"]=$scope.editEntity.name;
    	editEntity["realName"]=$scope.editEntity.realName;
    	editEntity["email"]=$scope.editEntity.email;
    	editEntity["departmentId"]=$scope.editEntity.departmentId;
    	editEntity["phone"]=$scope.editEntity.phone;
    	editEntity["password"]=$scope.editEntity.password;
    	editEntity["confirmPassword"]=$scope.editEntity.confirmPassword;
    	editEntity["roleIds"]=$scope.editEntity.roleIds;
    	editEntity["accountNonExpired"]=$scope.editEntity.accountNonExpired;
    	editEntity["accountNonLocked"]=$scope.editEntity.accountNonLocked;
    	
    	var requestJson=JSON.stringify(editEntity);
    	
   		$(".modal-dialog").block({message:'正在执行操作，请稍等...'});
   		
		$http.post('api/core/access/user/update',{params:{"requestJson":requestJson}}).success(function(data, status, headers, config) {
			$(".modal-dialog").unblock();
			modalService.showAlertModal('注意',data.message);
			if(data.status==1){
				$("#editModal").modal("hide");
				$scope.loadData();
			}
		}).error(function(data, status, headers, config) {
			$(".modal-dialog").unblock();
	    	
        });  
	};
	
	$scope.doDelete=function(entity){
		if(!confirm("确认删除 “" + entity.name + "” 吗？")){
			return ;
		}
		$("body").block({ message:'正在执行操作，请稍等...',css: { top: '50%' } });
		$http.post('api/core/access/user/deleteById',{params:{"id":entity.id}}).success(function(data, status, headers, config) {
			modalService.showAlertModal('注意',data.message);
			$("body").unblock();
			if(data.status==1){
				$scope.loadData(); 
			}
		}).error(function(data, status, headers, config) {
			$("body").unblock();
	    	
       });  
	}
    
	  $scope.initTreeForEdit=function(orgIds){
		  var orgIdsArray=convertToIntegerArray(orgIds.split(","));
    	   for(var i=0;i<$scope.orgData.length;i++){
			   if(orgIdsArray.indexOf($scope.orgData[i].id)>=0){
				   $scope.orgData[i].checked=true;
			   }else{
				   $scope.orgData[i].checked=false;
			   }
			 
		   }
		   $scope.initTree($scope.orgData,"organizationTreeForEdit");
	  }
	
	 
	$scope.orgData=[];
	
  
    
  
    
    $scope.initTree=function(zNodes,treeId){
    	var setting = {
    			check: {
    				enable: true
    			},
    			data: {
    				simpleData: {
    					enable: true
    				}
    			}
    		};
    	$.fn.zTree.init($("#"+treeId), setting, zNodes);	
    	$.fn.zTree.getZTreeObj(treeId).setting.check.chkboxType={ "Y" : "ps", "N" : "ps" };
    };
    
   

    $scope.getNodesId=function(nodes){
    	var retVal=new Array();
    	for(var i=0;i<nodes.length;i++){
    		retVal.push(nodes[i].id);
    	}
    	return retVal;
    }
    
    
    
    
      var updateSelected = function(selected,action,id,name){ 
	    if(action == 'add' && selected.indexOf(id) == -1){ 
	      selected.push(id); 
	     } 
	    if(action == 'remove' &&selected.indexOf(id)!=-1){ 
	      var idx = selected.indexOf(id); 
	      selected.splice(idx,1); 
	    }
	   } 
	  
	  $scope.updateSelection = function(selected,$event, id){ 
	    var checkbox = $event.target; 
	    var action = (checkbox.checked?'add':'remove'); 
	    updateSelected(selected,action,id,checkbox.name); 
	   
	  } 
	  
	  $scope.isSelected = function(selected,id){ 
	    return selected.indexOf(id)>=0; 
	  } 
	  
	  $scope.showDepartmentTree=function(){
		  $scope.departmentTreeShow=true;
	  }
	  
	  $scope.showDepartmentTreeForEdit=function(){
		  $scope.departmentTreeForEditShow=true;
	  }
	  
	  
	  function initDepartmentTree(data){
			$.fn.zTree.init($("#departmentTree"),{
				view: {
					dblClickExpand: false
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					beforeClick: function(treeId,treeNode) {
					
						return true;
					},
					onClick: function(e, treeId, treeNode) {
						var zTree = $.fn.zTree.getZTreeObj("departmentTree"),
						nodes = zTree.getSelectedNodes(),
						v = "";
						nodes.sort(function compare(a,b){return a.id-b.id;});
						for (var i=0, l=nodes.length; i<l; i++) {
							v += nodes[i].name + ",";
						}
						if (v.length > 0 ) v = v.substring(0, v.length-1);
						$scope.departmentName=v;
						$scope.entity["departmentId"]=treeNode.id;
					    $scope.departmentTreeShow=false;
						$scope.$apply();//更新数据
					}
				}
			},data);
			
			$.fn.zTree.init($("#departmentTreeForEdit"),{
				view: {
					dblClickExpand: false
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					beforeClick: function(treeId,treeNode) {
					
						return true;
					},
					onClick: function(e, treeId, treeNode) {
						var zTree = $.fn.zTree.getZTreeObj("departmentTreeForEdit"),
						nodes = zTree.getSelectedNodes(),
						v = "";
						nodes.sort(function compare(a,b){return a.id-b.id;});
						for (var i=0, l=nodes.length; i<l; i++) {
							v += nodes[i].name + ",";
						}
						if (v.length > 0 ) v = v.substring(0, v.length-1);
						$scope.editDepartmentName=v;
						$scope.editEntity["departmentId"]=treeNode.id;
					    $scope.departmentTreeForEditShow=false;
						$scope.$apply();//更新数据
					}
				}
			},data);
	  }
	  
	 
	  $scope.loadInitDepartmentData=function(){
			var submitData={};
			$http.post('api/core/access/department/getZTreeJSON',{params:submitData}).success(function(data, status, headers, config) {
				initDepartmentTree(data.data);
			}).error(function(data, status, headers, config) {
		    	alert(data);
	        });  
	  }
	  $scope.loadInitDepartmentData();
	  
	  
	    /**
	     * 求arr1,arr2的差集
	     * arr1,arr2本身会被裁剪
	     */
		$scope.arraySubtract=function(arr1,arr2){
			for (var i = arr1.length - 1; i >= 0; i--) {
			    a = arr1[i];
			    for (var j = arr2.length - 1; j >= 0; j--) {
			        b = arr2[j];
			        if (a == b) {
			            arr1.splice(i, 1);
			            arr2.splice(j, 1);
			            break;
			        }
			    }
			}
			return arr1;
		}
		

		
		
	//-------------------
		$scope.selectedRoleForQuery=[];
		$scope.showRoleListModal=function(){
			
			$("#roleListModal").modal("show");
		}
		
        $scope.hideRoleListModal=function(){
        	for(var i=0;i<$scope.selectedRoleForQuery.length;i++){
      		  if(i!=0){
      			 $scope.roleNameForQuery=$scope.roleNameForQuery+",";
      		  }
      		  $scope.roleNameForQuery=$scope.roleNameForQuery+$scope.roleMap["r"+$scope.selectedRoleForQuery[i]].nameZh;
      	     }
			$("#roleListModal").modal("hide");
		}
        $scope.queryEntity={};
        $scope.roleNameForQuery="";

		
		
	
});
